package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.dao.OrderSettingListDao;
import com.itheima.entity.PageResult;

import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderSettingListService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;


import java.util.*;

@Service(interfaceClass = OrderSettingListService.class)
@Transactional
public class OrderSettingListServiceImpl implements OrderSettingListService {

    @Autowired
    private OrderSettingListDao orderSettingListDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;


    @Override
    public PageResult findPage(Map map) throws Exception {
        Integer currentPage = (Integer) map.get("currentPage");
        Integer pageSize = (Integer) map.get("pageSize");

        Map param = new HashMap();
        param.put("queryString",(String) map.get("queryString"));
        param.put("orderStatus",(String) map.get("orderStatus"));
        param.put("orderType",(String) map.get("orderType"));

        String orderStatus = (String) map.get("orderStatus");
        String orderType = (String) map.get("orderType");
        List<String> orderDate = (List)  map.get("orderDate");
        String begin = null;
        String end = null;
        //判断日期是否为空
        if(orderDate!=null && orderDate.size()>0){
            begin = orderDate.get(0);
            end = orderDate.get(1);
        }
        param.put("begin",begin);
        param.put("end",end);

        //使用分页助手插件实现分页查询
        PageHelper.startPage(currentPage,pageSize);
        Page<Order> page = orderSettingListDao.findByCondition(param);

        return new PageResult(page.getTotal(),page.getResult());

    }

    /**
     * 查询所有套餐信息
     * @return
     */
    @Override
    public List<Setmeal> findAll() {
        return orderSettingListDao.findAll();
    }

    /**
     * 新增电话预约
     * @param map
     * @return
     */
    @Override
    public Result order(Map map) throws Exception {
        /**
         1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
         2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
         3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
         4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
         5、预约成功，更新当日的已预约人数
         */

        //获取日期


        String orderDate = (String) map.get("orderDate");
//        Date orderDate1 = orderSetting.getOrderDate();
//        String date1 = DateUtils.parseDate2String(orderDate1);
        String[] split = orderDate.split("T");
        String[] split1 = split[0].split("-");
        int m=Integer.parseInt(split1[2])+1 ;
        String g=split1[0]+"-"+split1[1]+"-"+m;
//        Date date2 = DateUtils.parseString2Date(g);
//        orderSetting.setOrderDate(date2);



        //使用工具类转换日期的格式
        Date date = DateUtils.parseString2Date(g);
        //根据日期查询预约设置信息
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if(orderSetting == null){
            //没有进行预约设置，不能进行预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //判断当前已预约数是否大于等于可预约数
       if(orderSetting.getReservations() >= orderSetting.getNumber()){
           //所选日期已经约满，无法进行预约
           return new Result(false,MessageConstant.ORDER_FULL);
       }

       //判断当前会员是否重复预约
        String phoneNumber = (String) map.get("phoneNumber");
        Member member = memberDao.findByTelephone(phoneNumber);
        if(member!=null) {
            Integer memberId = member.getId();//会员id
            Integer setmealId = Integer.parseInt((String) map.get("setmealIds"));//套餐id
            Order order = new Order(memberId, date, setmealId);
            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                //用户正在重复预约，不能进行预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }

            //根据手机号判断当前用户是否是会员，如果不是，则需要自动完成注册
            if(member == null){
                member = new Member();
                member.setName((String) map.get("name"));
                member.setPhoneNumber(phoneNumber);
                member.setIdCard((String) map.get("idCard"));
                member.setSex((String) map.get("sex"));
                member.setRegTime(new Date());
                memberDao.add(member);
            }

            //预约成功，保存预约信息，更新当日预约人数
            Order order = new Order(member.getId(),
                    date,
                    (String) map.get("orderType"),
                    Order.ORDERSTATUS_NO,
                    Integer.parseInt((String) map.get("setmealIds")));
            orderDao.add(order);

            //更新当前预约人数
        int reservations = orderSetting.getReservations();
        orderSetting.setReservations(reservations+1);//设置已预约人数+1
//        System.out.println(orderSetting);



        orderSettingDao.editReservationsByOrderDate(orderSetting);
        //调用预约设置dao
        //返回结果，并将订单id返回供预约成功页面使用
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 回显编辑中的基本信息
     * @param id
     * @return
     */@Override

    public Map findById(Integer id) throws Exception {
        Map map = orderSettingListDao.findById(id);
        map.put("orderDate",DateUtils.parseDate2String((Date) map.get("orderDate")));
        return map;
    }

    /**
     * 编辑修改预约信息
     * @param order
     */
    @Override
    public void edit(Order order) {
        orderSettingListDao.edit(order);

    }

    /**
     * 根据预约订单id删除某预约
     * @param id
     */
    @Override
    public void delete(Integer id) {
        orderSettingListDao.delete(id);
    }


    //使用开关修改状态
    @Override
    public void changeStatus(Map<String, Object> map) {
        Integer id = (Integer) map.get("id");
        String orderStatus = (String) map.get("orderStatus");
        Order order = orderDao.findById(id);
        if (order != null) {
            order.setOrderStatus(orderStatus);
            map.put("orderStatus", orderStatus);
            orderDao.changeStatus(map);
        }
    }
}
